package com.sofwin.realm;

import com.sofwin.pojo.SysUser;
import com.sofwin.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.List;

public class UserRealm extends AuthorizingRealm {

    private UserService userService;

    /**
     * 授权
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String  userName = principalCollection.getPrimaryPrincipal().toString();// 获取登录名
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        SysUser user = new SysUser();
        user.setLoginAccount(userName);
         user = userService.selectUser(user);
         info.addRole(String.valueOf(user.getRoleId()));
//        info.addRole();// 给当前主体增加一个橘色 addRoles
//        info.addStringPermission();// 给当前主体增加权限
        List<String> permissions = userService.selectUserPermssionsByRoleId(user.getRoleId());
        info.addStringPermissions(permissions);
        System.out.println("授权...........");
        return info;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token =(UsernamePasswordToken)authenticationToken;
        String userName = token.getUsername();
        String password = new String(token.getPassword());
        boolean hasUserName = userService.selectUserByName(userName);
        if(!hasUserName){
            throw new UnknownAccountException();
        }
        SysUser user = new SysUser();
        user.setLoginAccount(userName);
        user.setLoginPwd(password);
        boolean right = userService.checkLogin(user);
        if(!right){
            throw new IncorrectCredentialsException();
        }
        return new SimpleAuthenticationInfo(userName,password,"userRealm");
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }
}
